<!-- 备份：Team 原始版 增加 部门，组别，岗位列 -->
<template>
  <div class="team">
    <div class="form-container">
      <el-form ref="formRef" :inline="true" :model="queryForm" class="query-form" label-width="40px">
        <el-form-item label="用户名" label-width="60px">
          <el-input v-model="queryForm.user" clearable placeholder="请输入" style="width: 100px" />
        </el-form-item>
        <el-form-item label="部门">
          <el-cascader :options="deptList" :props="deptProps" style="width: 340px" v-model="queryForm.deptIds" collapse-tags clearable />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="queryForm.timelogCategory" placeholder="选择" style="width: 80px">
            <el-option label="全部类型" value="" />
            <el-option v-for="item in projectTypes" :key="item.dictCode" :label="`${item.dictLabel}`" :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="项目" v-if="queryForm.timelogCategory === '0'">
          <el-select v-model="queryForm.projectId" placeholder="全部项目" style="width: 160px">
            <el-option label="全部项目" value="" />
            <el-option v-for="item in projectList" :key="item.code" :label="`${item.code}-${item.cname}`" :value="item.id" />
          </el-select>
        </el-form-item>
        <TimeSlotDatePicker label="时段" v-model="queryForm.date" />
        <el-form-item>
          <el-button type="primary" @click="onSubmit" :icon="Search">查询</el-button>
          <el-button @click="handleClickBtnReset" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="team-container" ref="tableContainer">
      <el-table v-if="flag" :data="tableData" style="width: 100%" :span-method="objectSpanMethod" :height="tableHeight">
        <el-table-column prop="deptName" label="部门" width="120" fixed />
        <el-table-column prop="deptName" label="组别" width="120" fixed />
        <el-table-column prop="deptName" label="岗位" width="120" fixed />
        <el-table-column prop="username" label="姓名" width="180" fixed class-name="td-column-username">
          <template #default="scope">
            <div>{{ scope.row.userNick }}</div>
            <div>({{ scope.row.username }})</div>
          </template>
        </el-table-column>
        <el-table-column prop="time" label="时间" width="120" fixed />
        <el-table-column v-for="(item, idx) in tableColumnDate" :key="idx" :prop="item" :label="item" width="120">
          <el-table-column label="类型" width="180">
            <template #default="scope">
              <template v-if="scope.row[item + '_timelogCategory'] == 0"> {{ scope.row[item + '_ProjectCode'] }}-{{ scope.row[item + '_ProjectName'] }}</template>
              <template v-else-if="scope.row[item + '_timelogCategory'] > 0">{{ getProjectTypeByCode(scope.row[item + '_timelogCategory']) }}</template>
            </template>
          </el-table-column>
          <el-table-column label="任务名+说明" width="280">
            <template #default="scope">
              <template v-if="scope.row[item + '_StatementIsMax']">
                <el-popover placement="right" :width="400">
                  <template #reference>
                    <div class="statement">
                      {{ scope.row[item + '_Statement'] }}
                    </div>
                  </template>
                  <div class="statement-detail">
                    {{ scope.row[item + '_Statement'] }}
                  </div>
                </el-popover>
              </template>
              <div v-else class="statement">
                {{ scope.row[item + '_Statement'] }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="工时" :prop="item + '_durationTime'" width="60" />
        </el-table-column>
        <el-table-column></el-table-column>
        <el-table-column v-if="false" fixed="right" label="操作" min-width="80">
          <template #default>
            <el-button link type="primary" size="small">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination" v-if="false">
      <el-pagination v-model:current-page="currentPage4" v-model:page-size="pageSize4" :page-sizes="[100, 200, 300, 400]" layout="total, sizes, prev, pager, next, jumper" :total="400" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import http from '../http'
import * as utils from '../utils'
import { useProjectssStore, useDeptStore, useTaskTypeStore } from '../stores'
import IProjectTypes from '../interface/IProjectTypes'
import { Refresh, Search } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import _ from 'lodash'
import TimeSlotDatePicker from '../layout/FormTableLayout/TimeSlotDatePicker.vue'

// const usersStore = useUsersStore()
const projectssStore = useProjectssStore()
const deptStore = useDeptStore()

const formRef = ref<FormInstance>()
const timeDates = ['08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00']
const tableContainer = ref<HTMLElement | null>(null)
const projects = ref<{ [key: string]: string }>({})
const flag = ref(false)
const tableHeight = ref(500)
const tableData = ref<any[]>([])
const dataResult = ref()
const queryForm = reactive({
  user: '',
  projectId: '',
  date: [] as Date[],
  deptIds: [] as string[] | number[],
  timelogCategory: '',
})
const currentPage4 = ref(4)
const pageSize4 = ref(100)
const tableColumnDate = ref<string[]>([])
const projectTypes = ref<IProjectTypes[]>(useTaskTypeStore().getAllState())
const projectList = ref<Array<{ id: number; code: string; cname: string }>>(projectssStore.getAllState() as any)
const deptList = ref(deptStore.getAllState())
const deptProps = ref({ multiple: true, label: 'deptName', value: 'deptId' })


onMounted(async () => {
  const [start, end] = utils.getDateRangeByDate(utils.shortcutsType.本周) as Date[]

  const temp: { [key: string]: string } = {}

  projects.value = temp
  queryForm.date = [start, end]
  await initDate(start, end)
})

/**
 * 初始化日期范围并处理相关数据
 *
 * @param start 开始日期
 * @param end 结束日期
 * @returns 无返回值
 */
const initDate = async (start: Date, end: Date) => {
  // queryForm.date[0], queryForm.date[1]
  setTableColumn(start, end)
  await getTimelog(start, end)
  // console.log('tableColumnDate', tableColumnDate.value)
  nextTick(() => {
    dataResult.value = countByNameAndIndex()
    flag.value = true
    calculateTableHeight()
  })
}
const getProjectTypeByCode = (code: number) => {
  const item: any = projectTypes.value.find((e: any) => e.dictValue == code)
  if (item) {
    return item.dictLabel
  } else {
    return ''
  }
}

/**
 * 获取两个日期之间的所有日期（包含起始和结束日期）
 *
 * @param startDateStr 起始日期字符串或Date对象
 * @param endDateStr 结束日期字符串或Date对象
 * @returns 返回包含起始和结束日期之间所有日期的数组，格式为 YYYY-MM-DD 字符串
 */
const getAllDatesBetween = (startDateStr: string | Date, endDateStr: string | Date) => {
  const startDate = new Date(startDateStr)
  const endDate = new Date(endDateStr)

  let currentDate = new Date(startDate)
  const dates = []

  while (currentDate <= endDate) {
    // 使用 toISOString() 并分割以获得 YYYY-MM-DD 格式的日期字符串
    dates.push(utils.formatDate(currentDate, 'yyyy-MM-dd'))
    // 设置日期为下一天
    currentDate.setDate(currentDate.getDate() + 1)
  }

  return dates
}

/**
 * 设置表格列的日期范围
 *
 * @param start 开始日期
 * @param end 结束日期
 */
const setTableColumn = (start: Date, end: Date) => {
  tableColumnDate.value = getAllDatesBetween(start, end)
}
/**
 * 计算字符串中英文字符数量
 *
 * @param str 需要计算的字符串
 * @returns 返回字符串中英文字符的总数
 */
function countEnglishCharacters(str: string) {
  let englishCount = 0
  for (let char of str) {
    if (/[a-zA-Z0-9]/.test(char)) {
      englishCount++
    } else if (char.charCodeAt(0) > 127) {
      // 非 ASCII 字符（中文字符等），通常占用两个英文字符位置
      englishCount += 2
    } else {
      englishCount++
    }
  }
  return englishCount
}
/**
 * 获取时间日志
 *
 * @returns Promise<void> 返回一个Promise对象，表示异步操作的结果
 */
const getTimelog = async (start: Date, end: Date) => {
  const deptIds: any[] = []
  queryForm.deptIds.forEach((e: any) => {
    deptIds.push(e[e.length - 1])
  })
  // queryForm.user = usersStore.user.username
  console.log('queryForm.user', queryForm.user)
  const params = {
    // userName: usersStore.user.username,
    pageSize: 99999,
    startTimelogDate: utils.formatDate(start, 'yyyy-MM-dd'),
    endTimelogDate: utils.formatDate(end, 'yyyy-MM-dd'),
  }
  // if (queryForm.user !== '') {
  //   Object.assign(params, { userName: queryForm.user })
  // }
  if (queryForm.user !== '') {
    Object.assign(params, { userName: `%${queryForm.user}%` })
  }
  if (queryForm.projectId !== '') {
    Object.assign(params, { projectId: queryForm.projectId })
  }
  if (queryForm.timelogCategory !== '') {
    Object.assign(params, { timelogCategory: queryForm.timelogCategory })
  }
  if (deptIds.length > 0) {
    Object.assign(params, { deptIds: deptIds.join(',') })
  }
  const res = await http({
    method: 'GET',
    path: '/dev-api/oa/timelog/listby',
    params,
  })
  // localhost/dev-api/oa/timelog/listby?userName=admin&projectId=662&deptIds=103,104&timelogCategory=3
  const { code, rows } = res
  // testDate(rows)
  const result: any[] = []
  const groupedData: any = {}

  if (code === 200) {
    const tempArr = _.orderBy(rows, ['startTime'], ['asc'])
    // timeDates
    const newDate: any[] = []
    const userNameCounts = _.countBy(rows, 'userName')

    // 组合新的日期数组
    for (const key in userNameCounts) {
      const userName = key
      for (let index = 0; index < timeDates.length - 1; index++) {
        newDate.push({ userName, time: timeDates[index] + '-' + timeDates[index + 1] })
      }
    }
    // console.log(' ==== TEAM2 ==== newDate', newDate)

    tempArr.forEach((e: any) => {
      const { userName, startTime, endTime } = e
      // console.log(' ==== TEAM 1 ==== { userName, startTime, endTime }', { userName, startTime, endTime })
      const time = startTime.slice(-5) + '-' + endTime.slice(-5)
      // 按姓名分组
      if (!groupedData[userName]) {
        groupedData[userName] = {}
      }
      if (!groupedData[userName][time]) {
        groupedData[userName][time] = []
      }
      // 按时间分组
      groupedData[userName][time].push(e)
    })
    // console.log(' ==== TEAM2 ==== groupedData', groupedData)
    for (const key in groupedData) {
      // console.log(' ==== TEAM2 ==== key', key)
      const tempArr: any[] = []
      for (const key2 in groupedData[key]) {
        // console.log(' ==== TEAM2 ==== key2', key2)
        const tempObj: any = {}
        for (let index = 0; index < groupedData[key][key2].length; index++) {
          const element = groupedData[key][key2][index]
          const keyCode = element.timelogDate
          tempObj.orderTime = utils.formatDate(new Date(), 'yyyy-MM-dd') + ' ' + utils.formatDate(new Date(element.startTime), 'HH:mm')
          tempObj.startTime = element.startTime
          tempObj.userNick = element.userNick
          tempObj.deptName = element.deptName
          const statement = element.remark
          tempObj[`${keyCode}_Statement`] = statement
          tempObj[`${keyCode}_StatementIsMax`] = countEnglishCharacters(statement) > 100
          tempObj[`${keyCode}_ProjectId`] = element.projectId
          tempObj[`${keyCode}_ProjectName`] = element.projectName
          tempObj[`${keyCode}_ProjectCode`] = element.projectCode
          tempObj[`${keyCode}_timelogCategory`] = element.timelogCategory
          tempObj[`${keyCode}_deptId`] = element.deptId
          tempObj[`${keyCode}_durationTime`] = element.durationTime
          // console.log(' ==== TEAM2 ==== element', element)
        }
        tempArr.push({ username: key, time: key2, ...tempObj })
        // result.push({ username: key, time: key2, ...tempObj })
      }
      const newTempArr = _.orderBy(tempArr, ['orderTime'], ['asc'])
      result.push(...newTempArr)
      // console.log(' ==== TEAM2 ==== tempArr', tempArr)
    }
  }
  // console.log(' ==== TEAM2 ==== result', result)
  // console.log('res ——', _.overflow(result, 'userName'))
  tableData.value = result
}
// 计算el-table的高度
const calculateTableHeight = () => {
  if (tableContainer.value) {
    tableHeight.value = tableContainer.value.offsetHeight // 计算并设置高度
  }
}
/**
 * 根据名称和索引统计数量
 *
 * @returns 返回一个对象，键为首次出现的索引，值为一个数组，包含名称出现的次数和标志位1
 */
const countByNameAndIndex = () => {
  const nameCountMap: { [key: string]: number } = {}
  const firstIndexMap: { [key: string]: number } = {}
  tableData.value.forEach((item: any, index) => {
    if (!nameCountMap[item.username]) {
      nameCountMap[item.username] = 1
      firstIndexMap[item.username] = index
    } else {
      nameCountMap[item.username]++
    }
  })

  const mergedObject: { [key: string]: Array<number> } = {}
  for (const name in nameCountMap) {
    mergedObject[firstIndexMap[name]] = [nameCountMap[name], 1]
  }
  // console.log('mergedObject firstIndexMap', firstIndexMap)
  // console.log('mergedObject nameCountMap', nameCountMap)
  // console.log('mergedObject tableData', tableData)
  // console.log('mergedObject B', mergedObject)
  return mergedObject
}

/**
 * 对象跨列方法
 *
 * @param row 行对象
 * @param column 列对象
 * @param rowIndex 行索引
 * @param columnIndex 列索引
 * @returns 返回一个数组，表示该单元格应横跨的列数和行数
 */
const objectSpanMethod = ({ rowIndex, columnIndex }: any) => {
  if (columnIndex <= 3) {
    let res = dataResult.value[rowIndex]
    if (res) {
      return res
    } else {
      return [0, 0]
    }
  }
}

/**
 * 提交表单处理函数
 *
 * @returns {Promise<void>} 返回一个异步操作的Promise对象，无返回值
 */
const onSubmit = async () => {
  // console.log('queryForm', queryForm)
  if (queryForm.date.length == 2) {
    await initDate(queryForm.date[0], queryForm.date[1])
  }
}
/**
 * 重置按钮点击事件处理函数
 *
 * @returns 无返回值
 */
const handleClickBtnReset = async () => {
  const [start, end] = utils.getDateRangeByDate2(utils.shortcutsType.本周) as Date[]
  queryForm.user = ''
  queryForm.projectId = ''
  queryForm.date = [start, end]
  queryForm.deptIds = [] as string[] | number[]
  queryForm.timelogCategory = ''
  if (queryForm.date.length == 2) {
    await initDate(queryForm.date[0], queryForm.date[1])
  }
}
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
}
</script>
<style lang="scss">
.td-column-username {
  text-align: center !important;
}
</style>
<style scoped lang="scss">
.team {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  position: absolute;
  left: 0;
  top: 0;
  .form-container {
    display: flex;
    justify-content: flex-start;
  }
  .team-container {
    flex: 1;
    overflow: hidden;
    margin-bottom: 0px;
  }
  .pagination {
    display: flex;
    justify-content: flex-end;
  }
  .statement {
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
</style>
